﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MoroMoro.Samples.ToDoList.Base.Application;
using MoroMoro.Samples.ToDoList.Application;
using MoroMoro.Samples.ToDoList.Domain.Categories;
using MoroMoro.Samples.ToDoList.Presentation.Views.Categories;
using MoroMoro.Samples.ToDoList.Presentation.ErrorMessages.Categories;

namespace MoroMoro.Samples.ToDoList.Presentation.Presenters.Categories
{
    /// <summary>
    /// カテゴリ構築プレゼンターです。
    /// </summary>
    /// <typeparam name="TView">ビューの型。</typeparam>
    /// <typeparam name="TErrors">エラーの型。</typeparam>
    public abstract class CategoryBuildPresenter<TView, TErrors> : BuildPresenter<TView, Category, Category.Builder, TErrors>
        where TView : ICategoryBuildView
        where TErrors : EntityBuildErrors
    {
        /// <summary>
        /// <see cref="CategoryBuildPresenter&lt;TView, TErrors&gt;"/> クラスの新しいインスタンスを初期化します。
        /// </summary>
        /// <param name="view">ビュー。</param>
        /// <param name="facade">ファサード。</param>
        /// <param name="builder">ビルダ。</param>
        /// <exception cref="System.ArgumentNullException">view または facade または builder が null です。</exception>
        public CategoryBuildPresenter(TView view, ToDoListFacade facade, Category.Builder builder)
            : base(view, facade, builder)
        {
        }


        /// <inheritdoc/>
        protected override void RegisterEventHandlers()
        {
            base.RegisterEventHandlers();

            View.NameTextChanged += OnNameTextChanged;
        }

        /// <summary>
        /// カテゴリの名前入力フィールドのテキストが変更された時の処理を行います。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnNameTextChanged(object sender, EventArgs e)
        {
            if (string.Equals(Builder.Name, View.Name, StringComparison.Ordinal))
            {
                return;
            }
            Builder.Name = View.Name;
            HasChange = true;
            UpdateInputErrors();
        }


        /// <inheritdoc/>
        protected override void UpdateInputErrors()
        {
            var categoryBuildErrorMessage = new CategoryBuildErrorMessage();

            Builder.NotifyNameErrorTo(categoryBuildErrorMessage);
            View.SetNameError(categoryBuildErrorMessage.ToString());
            categoryBuildErrorMessage.Clear();
        }
    }
}
